package com.datviet.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.datviet.dao.IUserDAO;
import com.datviet.domain.UserRegisterDto;
import com.datviet.entity.User;

@Component
public class UserRegisterValidator implements Validator {

	@Autowired
	private IUserDAO userDao;
	
	@Override
	public boolean supports(Class<?> clazz) {
		return UserRegisterDto.class.equals(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "username.empty", "defaultMessage");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.empty");
		UserRegisterDto userRegister = (UserRegisterDto) target;
		if(StringUtils.hasText(userRegister.getUsername())){
			User existedUser = userDao.selectUserByName(userRegister.getUsername().trim());
			if(existedUser != null){
				errors.rejectValue("username", "username.existed");
			}
		}
	}

}
